package model

import (
	"fmt"
	"gowork/callBarring/utils"
	"time"
)

type Account struct {
	AccountId int64 `xorm:"pk autoincr"`
	DepartMentId int64
	AccountName string
	Line int
	Level int
	Incumbency int
	CreatedAt time.Time
	UpdatedAt time.Time
}

type Customer struct {
	CustomerId int64 `xorm:"pk autoincr"`
	CustomerName string
	CustomerType int
	FounderId int64
	FounderName string
	BelongerId int64
	BelongerName string
	AllocationTime time.Time
	CallOutNumber int `xorm:"-"`
	CallLimit int  // 1不限制  2限制
	LiftingRestrictionsTime time.Time
	CreatedAt time.Time
	UpdatedAt time.Time
}

type Order struct {
	OrderId int64 `xorm:"pk autoincr"`
	OrderType int
	OrderState int
	CustomerId int64
	CustomerName string
	NextSinglePersonId int64
	NextSinglePersonName string
	MealList string
	TotalPrice float64
	Region string
	CreatedAt time.Time
	UpdatedAt time.Time
}

type CallRecord struct {
	CallRecordId int64 `xorm:"pk autoincr"`
	CustomerId int64
	CustomerName string
	AccountId int64
	AccountName string
	CallType int
	CallState int
	CallTime int64
	StartTime time.Time
	CreatedAt time.Time
	UpdatedAt time.Time
}

func (customer *Customer)CallOut(aId int64, cId int64, ct int, cs int, ci int64)(map[string]interface{}, error){

	w := new(utils.Worker)

	var a Account
	x.Id(aId).Get(&a)

	var c Customer
	x.Where("customer_id = ?", cId).Get(&c)

	var crTomLsit []*CallRecord
	x.SQL("select * from call_record where customer_id = ? and call_type = ? and call_time <= ? and created_at >= ?", cId, 1, 30, c.AllocationTime.Format("2006-01-02 15:04:05")).Find(&crTomLsit)
	//x.Where("customer_id = ?", cId).And("call_type = ?", 2).And("call_time <= ?", 30).And("created_at >= ?", c.AllocationTime.Format("2006-01-02 15:04:05")).Find(&crTomLsit)

	loadLocation, lErr := time.LoadLocation("Asia/Shanghai")
	if lErr != nil {
		return map[string]interface{}{"code": 400, "mesage": "呼出失败"}, lErr
	}

	if c.CustomerType < 4 {

		var crList []*CallRecord
		x.SQL("select * from call_record where customer_id = ? and call_type = 2 and start_time like ?", cId, time.Now().Format("2006-01-02")+"%").Find(&crList)
		//x.Where("customer_id = ?", cId).And("call_type = ?", 2).And("start_time like ?", time.Now().Format("2006-01-02")+"%").Find(&crList)
		if len(crList) > 0 {
			var cr = CallRecord{
				CallRecordId: w.GetId(),
				CustomerId:   c.CustomerId,
				CustomerName: c.CustomerName,
				AccountId:    a.AccountId,
				AccountName:  a.AccountName,
				CallType:     ct,
				CallState:    cs,
				CallTime:     ci,
				StartTime:    time.Now(),
				CreatedAt:    time.Now(),
				UpdatedAt:    time.Now(),
			}
			x.Insert(&cr)

			return map[string]interface{}{"code": 200, "message": "呼出成功"}, nil
		} else {

			var crNowList []*CallRecord
			x.SQL("select * from call_record where customer_id = ? and call_type = 1 and call_time <= 30 and start_time like ? order by created_at desc limit 3", cId, time.Now().Format("2006-01-02")+"%").Find(&crNowList)
			//x.Where("customer_id = ?", cId).And("call_type = ?", 1).And("call_time <= ", 30).
			//	And("start_time like ?", time.Now().Format("2006-01-02")+"%").Desc("created_at").Limit(3).Find(&crNowList)
			fmt.Println("crNowList：", crNowList)

			nowPlus, err := time.ParseInLocation("2006-01-02 15:04:05", time.Now().AddDate(0, 0, 1).Format("2006-01-02")+" 00:00:00", loadLocation)
			if err != nil {
				return map[string]interface{}{"code": 400, "mesage": "呼出失败"}, err
			}

			var twoList []*Order
			x.Join("INNER", "account", "account.account_id = order.next_single_person_id").
				Where("order.customer_id = ?", cId).And("account.line = ?", 2).
				And("order.order_state >= ?", 10).
				And("order.created_at >= ?", time.Now().AddDate(0, 0, -30).Format("2006-01-02 15:04:05")).
				Find(&twoList)
			fmt.Println("twoList：", twoList)

			if len(twoList) > 0 {

				if len(crTomLsit) >= 5 {
					var c Customer

					c.LiftingRestrictionsTime = nowPlus.AddDate(0, 0, 1)
					c.CallLimit = 2
					x.Id(cId).Update(&c)

					return map[string]interface{}{"code": 400, "message": "最近5次无效呼出,30天内有二线发货订单,1天后可拨打电话"}, nil
				}
			}

			var oneList []*Order
			x.Join("INNER", "account", "account.account_id = order.next_single_person_id").
				Where("order.customer_id = ?", cId).And("account.line = ?", 1).
				And("order.order_state >= ?", 10).
				And("order.created_at >= ?", time.Now().AddDate(0, 0, -30).Format("2006-01-02 15:04:05")).
				Find(&oneList)

			if len(oneList) > 0 && len(twoList) == 0 {
				var c Customer

				if len(crTomLsit) >= 5{
					c.LiftingRestrictionsTime = nowPlus.AddDate(0, 0, 1)
					c.CallLimit = 2
					x.Id(cId).Update(&c)

					return map[string]interface{}{"code": 400, "message": "最近5次无效呼出,30天内只有一线发货订单,1天后可拨打电话"}, nil
				}

				if len(crNowList) >= 3{
					c.LiftingRestrictionsTime = nowPlus
					c.CallLimit = 2
					x.Id(cId).Update(&c)

					return map[string]interface{}{"code": 400, "message": "连续3次无效呼出,30天内只有一线发货订单,当天限制呼出"}, nil
				}
			}

			var nineList []*Order
			x.Where("customer_id = ?", cId).
				And("order_state >= ?", 10).
				And("created_at >= ?", time.Now().AddDate(0, 0, -90).Format("2006-01-02 15:04:05")).
				And("created_at < ?", time.Now().AddDate(0, 0, -30).Format("2006-01-02 15:04:05")).
				Find(&nineList)
			if len(nineList) > 0 {
				var c Customer

				if len(crTomLsit) >= 5{
					c.LiftingRestrictionsTime = nowPlus.AddDate(0, 0, 3)
					c.CallLimit = 2
					x.Id(cId).Update(&c)
					return map[string]interface{}{"code": 400, "message": "最近5次无效呼出,30到90天内有发货订单,3天后可拨打电话"}, nil
				}

				if len(crNowList) >= 3{
					c.LiftingRestrictionsTime = nowPlus.AddDate(0, 0, 1)
					c.CallLimit = 2
					x.Id(cId).Update(&c)
					return map[string]interface{}{"code": 400, "message": "连续3次无效呼出,30到90天内有发货订单,1天后可拨打电话"}, nil
				}
			}

			var noList []*Order
			x.Where("customer_id = ?", cId).
				And("order_state >= ?", 10).
				And("created_at > ?", time.Now().AddDate(0, 0, -90).Format("2006-01-02 15:04:05")).
				Find(&noList)
			if len(noList) <= 0 {
				var c Customer

				if len(crTomLsit) >= 5{
					c.CallLimit = 2
					c.CustomerType = 5
					x.Id(cId).Update(&c)

					return map[string]interface{}{"code": 400, "message": "最近5次无效呼出,90天内无发货订单,该客户被标识成风险客户"}, nil
				}

				if len(crNowList) >= 3{
					c.LiftingRestrictionsTime = nowPlus.AddDate(0, 0, 7)
					c.CallLimit = 2
					x.Id(cId).Update(&c)

					return map[string]interface{}{"code": 400, "message": "连续3次无效呼出,90天内无发货订单,7天后可拨打电话"}, nil
				}
			}
		}
	}else if c.CustomerType == 4 {
		if len(crTomLsit) >= 3{
			var c Customer
			c.CallLimit = 2
			c.CustomerType = 5
			x.Id(cId).Update(&c)
			return map[string]interface{}{"code": 400, "message": "D类客户分配后3次无效呼出,该客户被标识成风险客户"}, nil
		}
	}

	var cr = CallRecord{
		CallRecordId: w.GetId(),
		CustomerId:   c.CustomerId,
		CustomerName: c.CustomerName,
		AccountId:    a.AccountId,
		AccountName:  a.AccountName,
		CallType:     ct,
		CallState:    cs,
		CallTime:     ci,
		StartTime:    time.Now(),
		CreatedAt:    time.Now(),
		UpdatedAt:    time.Now(),
	}
	x.Insert(&cr)

	return map[string]interface{}{"message": "呼出成功","code":"200"}, nil
}

func (customer *Customer)LiftingRestrictions(){

	var cLsit []*Customer
	x.Where("call_limit = ?", 2).Find(&cLsit)

	for _, cv := range cLsit{
		cv.CallLimit = 1
		x.Id(cv.CustomerId).Update(cv)
	}
}

func (customer *Customer)QueryUserInfo(cId int64)(*Customer, error){

	var c Customer
	x.Where("customer_id = ?", cId).Get(&c)

	var crTomLsit []*CallRecord
	x.SQL("select * from call_record where customer_id = ? and call_type = ? and call_time <= ? and created_at >= ?", cId, 1, 30, c.AllocationTime.Format("2006-01-02 15:04:05")).Find(&crTomLsit)
	//x.Where("customer_id = ?", cId).And("call_type = ?", 1).And("call_time <= ", 30).And("order.created_at >= ?", c.AllocationTime).Find(&crTomLsit)

	var crNowList []*CallRecord
	x.SQL("select * from call_record where customer_id = ? and call_type = 1 and call_time <= 30 and start_time like ? order by created_at desc limit 3", cId, time.Now().Format("2006-01-02")+"%").Find(&crNowList)
	//x.Where("customer_id = ?", cId).And("call_type = ?", 1).And("call_time <= ", 30).And("start_time like ?", time.Now().Format("2006-01-02")+"%").Find(&crNowList)

	var twoList []*Order
	x.Join("INNER", "account", "account.account_id = order.next_single_person_id").
		Where("order.customer_id = ?", cId).And("account.line = ?", 2).
		And("order.order_state >= ?", 10).
		And("order.created_at >= ?", time.Now().AddDate(0, 0, -30).Format("2006-01-02 15:04:05")).
		Find(&twoList)

	var crList []*CallRecord
	x.SQL("select * from call_record where customer_id = ? and call_type = 2 and start_time like ?", cId, time.Now().Format("2006-01-02")+"%").Find(&crList)

	fmt.Println("twoList：", twoList)
	continuity := 3 - len(crNowList)
	fmt.Println("continuity：", continuity)
	lately := 5 - len(crTomLsit)
	fmt.Println("lately：", lately)
	if continuity < lately{
		if len(twoList) > 0 || len(crList) >0{
			c.CallOutNumber = lately
		}else {
			c.CallOutNumber = continuity
		}
	}else {
		c.CallOutNumber = lately
	}

	return &c, nil
}

